package cn.edu.wfu.libautobook.quartz;

import cn.edu.wfu.libautobook.bean.Quartz;
import cn.edu.wfu.libautobook.bean.Schedule;
import cn.edu.wfu.libautobook.service.QuartzService;
import cn.edu.wfu.libautobook.service.ScheduleService;
import cn.edu.wfu.libautobook.utils.QuartzUtils;
import cn.edu.wfu.libautobook.utils.WebUtils;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class BookSeat extends QuartzJobBean {
    @Autowired
    private Scheduler scheduler;
    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private QuartzService quartzService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        // 获取事务的sid
        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        Integer sid = (Integer) jobDataMap.get("sid");
        // 获取预约对象
        Schedule schedule = scheduleService.getScheduleBySid(sid);
        Quartz quartz = schedule.getQuartz();
        // 删除预约事务
        QuartzUtils.deleteScheduleJob(scheduler, (String) jobDataMap.get("name"));
        // 判断是否未无效预约
        if (schedule.getEnabled() == 0 || schedule.getQuartz().getStatus() == 1) {
            return;
        }
        // 获取基本预约信息
        Integer pid = schedule.getUser().getPid();
        Integer seatId = schedule.getSeatId();
        String username = schedule.getUser().getUsername();
        Date orderDate = schedule.getTime();
        // 预约程序
        System.out.println("正在处理 " + username + "的在" + seatId + "位置的预约");
        boolean isSuccess = false;
        try {
            // 登陆
            isSuccess = login(pid, seatId, username, orderDate);
        }catch (Exception e) {
            e.printStackTrace();
        }
        // 数据库标识
        schedule.setUser(null);
        schedule.setQuartz(null);
        schedule.setEnabled(0);
        quartz.setStatus(1);
        if (isSuccess) {
            schedule.setStates(2);
            System.out.println("预约成功");
        } else {
            if (schedule.getAdjust() == 1) {
                // 调剂算法
                autoAdjust(schedule);
            }
            schedule.setStates(3);
            System.out.println("预约失败");
        }
        scheduleService.updateSchedule(schedule);
        quartzService.update(quartz);
    }

    /**
     * 自动调剂
     */
    public boolean autoAdjust(Schedule schedule) {
        return false;
    }

    /**
     * 处理返回值的乱码
     * @param str 要处理的值
     * @return 处理后的值
     */
    public String clearMisc(String str) {
        return str.replace("ï»¿\r\n\r\n\r\n\r\n", "");
    }

    public String getOrderDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        String r = String.format("%4d-%02d-%02d", calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DATE));
        return r;
    }

    public boolean bookRequest(String cookie, Integer seatId, String date) throws Exception {
        // 填入参数
        Map<String, Object> param = new HashMap<>();
        param.put("seat_id", seatId);
        param.put("order_date", date);
        // 填入Cookie
        Map<String, Object> header = new HashMap<>();
        header.put("Cookie", cookie);
        // 请求预约api
        String content = clearMisc(WebUtils.httpPostRequest("http://210.44.64.139/seat/seatOrderAction.php?action=addOrderSeat", header, param));
        JSONObject jsonObject = new JSONObject(content);
        return jsonObject.getBoolean("success");
    }

    public boolean login(Integer pid, Integer seatId, String username, Date orderDate) throws Exception {
        // 参数
        Map<String, Object> data = new HashMap<>();
        data.put("cardno", pid);
        // 初始化cookie
        String cookie = "";
        // 获取带header的响应
        Map<String, Object> resp = WebUtils.httpPostRequestHeader("http://210.44.64.139/touchscreen/seatOrderAction.php?action=payCardLogin", new HashMap<>(), data);
        // 取Header并找到Cookie
        Header[] header = (Header[]) resp.get("header");
        for (Header item:header) {
            if (item.getName().equals("Set-Cookie")) {
                cookie = item.getValue();
            }
        }
        // 清理Cookie
        cookie = cookie.replace("; path=/", "");
        String content = clearMisc((String) resp.get("content"));
        JSONObject jsonObject = new JSONObject(content);
        // 格式化时间
        String orderDateStr = getOrderDate(orderDate);
        // 判断是否登陆成功
        if ((boolean) jsonObject.get("success")) {
            System.out.println("用户 " + username + "已登陆成功");
            // 成功的处理流程
            return bookRequest(cookie, seatId, orderDateStr);
        }
        // 失败处理流程
        return false;
    }
}
